<template>
  <div class="post-detail-container">
    <a-card :bordered="false">
      <template #title>
        <div class="card-title">
          <a-button @click="goBack" type="link">
            <left-outlined /> 返回
          </a-button>
          <span>帖子详情</span>
        </div>
      </template>
      
      <a-spin :spinning="loading">
        <template v-if="post">
          <div class="post-header">
            <h1 class="post-title">{{ post.title }}</h1>
            <div class="post-meta">
              <a-tag :color="getTagColor(post.tagId)">{{ getTagName(post.tagId) }}</a-tag>
              <span class="post-author">
                <span class="author-avatar" :style="{ backgroundColor: post.userColor }">
                  {{ post.userNickname ? post.userNickname.substring(0, 1) : '用' }}
                </span>
                <span>{{ post.userNickname }}</span>
              </span>
              <span class="post-time">{{ formatDate(post.createTime) }}</span>
              <span class="post-likes">
                <heart-outlined /> {{ post.likes }} 点赞
              </span>
              <a-tag :color="post.status === 1 ? 'green' : 'red'">
                {{ post.status === 1 ? '正常' : '已禁用' }}
              </a-tag>
            </div>
          </div>
          
          <div class="post-content">
            {{ post.content }}
          </div>
          
          <div v-if="post.images && JSON.parse(post.images).length > 0" class="post-images">
            <template v-for="(image, index) in JSON.parse(post.images)" :key="index">
              <img :src="image" :alt="`图片${index + 1}`" @click="previewImage(index)" />
            </template>
          </div>
          
          <a-divider />
          
          <div class="post-actions">
            <a-space>
              <a-button type="primary" @click="changeStatus(post.id, post.status === 1 ? 0 : 1)">
                {{ post.status === 1 ? '禁用帖子' : '启用帖子' }}
              </a-button>
              <a-popconfirm
                title="确定要删除这条帖子吗？"
                @confirm="deletePost"
                okText="确定"
                cancelText="取消"
              >
                <a-button danger>删除帖子</a-button>
              </a-popconfirm>
            </a-space>
          </div>
          
          <a-divider orientation="left">评论列表 ({{ post.comments ? post.comments.length : 0 }})</a-divider>
          
          <a-list
            itemLayout="horizontal"
            :dataSource="post.comments || []"
            :pagination="{ 
              pageSize: 10,
              size: 'small',
              showTotal: total => `共 ${total} 条评论`
            }"
          >
            <template #renderItem="{ item }">
              <a-list-item :key="item.id">
                <template #actions>
                  <a-space>
                    <a-tag :color="item.status === 1 ? 'green' : 'red'">
                      {{ item.status === 1 ? '正常' : '已禁用' }}
                    </a-tag>
                    <a @click="changeCommentStatus(item.id, item.status === 1 ? 0 : 1)">
                      {{ item.status === 1 ? '禁用' : '启用' }}
                    </a>
                    <a-popconfirm
                      title="确定要删除这条评论吗？"
                      @confirm="() => deleteComment(item.id)"
                      okText="确定"
                      cancelText="取消"
                    >
                      <a>删除</a>
                    </a-popconfirm>
                  </a-space>
                </template>
                <a-list-item-meta>
                  <template #avatar>
                    <span class="comment-avatar" :style="{ backgroundColor: item.userColor }">
                      {{ item.userNickname ? item.userNickname.substring(0, 1) : '用' }}
                    </span>
                  </template>
                  <template #title>
                    <span>{{ item.userNickname }}</span>
                    <span class="comment-time">{{ formatDate(item.createTime) }}</span>
                  </template>
                  <template #description>
                    <div class="comment-content">{{ item.content }}</div>
                    <div class="comment-likes">
                      <heart-outlined /> {{ item.likes }} 点赞
                    </div>
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </template>
        
        <a-empty v-else description="帖子不存在或已被删除" />
      </a-spin>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import { message } from 'ant-design-vue';
import {
  LeftOutlined,
  HeartOutlined
} from '@ant-design/icons-vue';

const route = useRoute();
const router = useRouter();
const postId = route.params.id;

const post = ref(null);
const loading = ref(false);

// 标签相关
const tags = [
  { id: 0, name: '全部', color: '#8cc9a1' },
  { id: 1, name: '求助', color: '#f0ad4e' },
  { id: 2, name: '分享', color: '#5bc0de' },
  { id: 3, name: '讨论', color: '#d9534f' },
  { id: 4, name: '经验', color: '#9370db' },
  { id: 5, name: '饮食', color: '#28a745' },
  { id: 6, name: '运动', color: '#fd7e14' },
  { id: 7, name: '科普', color: '#17a2b8' }
];

// 获取标签名称
const getTagName = (tagId) => {
  const tag = tags.find(t => t.id === tagId);
  return tag ? tag.name : '未知';
};

// 获取标签颜色
const getTagColor = (tagId) => {
  const tag = tags.find(t => t.id === tagId);
  return tag ? tag.color : '#8cc9a1';
};

// 加载帖子详情
const loadPost = async () => {
  loading.value = true;
  try {
    const res = await axios.get(`/admin/api/community/posts/${postId}`);
    
    if (res.data.code === 0) {
      post.value = res.data.data;
    } else {
      message.error(res.data.message || '获取帖子失败');
      post.value = null;
    }
  } catch (error) {
    message.error('获取帖子失败: ' + error.message);
    post.value = null;
  } finally {
    loading.value = false;
  }
};

// 修改帖子状态
const changeStatus = async (id, status) => {
  try {
    const res = await axios.put(`/admin/api/community/posts/${id}/status`, {
      status
    });
    
    if (res.data.code === 0) {
      message.success('操作成功');
      loadPost();
    } else {
      message.error(res.data.message || '操作失败');
    }
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
};

// 修改评论状态
const changeCommentStatus = async (id, status) => {
  try {
    const res = await axios.put(`/admin/api/community/comments/${id}/status`, {
      status
    });
    
    if (res.data.code === 0) {
      message.success('操作成功');
      loadPost();
    } else {
      message.error(res.data.message || '操作失败');
    }
  } catch (error) {
    message.error('操作失败: ' + error.message);
  }
};

// 删除帖子
const deletePost = async () => {
  try {
    const res = await axios.delete(`/admin/api/community/posts/${postId}`);
    
    if (res.data.code === 0) {
      message.success('删除成功');
      router.push('/community/posts');
    } else {
      message.error(res.data.message || '删除失败');
    }
  } catch (error) {
    message.error('删除失败: ' + error.message);
  }
};

// 删除评论
const deleteComment = async (id) => {
  try {
    const res = await axios.delete(`/admin/api/community/comments/${id}`);
    
    if (res.data.code === 0) {
      message.success('删除成功');
      loadPost();
    } else {
      message.error(res.data.message || '删除失败');
    }
  } catch (error) {
    message.error('删除失败: ' + error.message);
  }
};

// 查看图片
const previewImage = (index) => {
  if (!post.value.images) return;
  
  const images = JSON.parse(post.value.images);
  if (images.length === 0) return;
  
  // 使用ant-design-vue的图片预览
  const { createVNode, render } = window.Vue;
  const { message, Modal } = window.antd;
  
  Modal.info({
    title: '图片预览',
    content: createVNode('img', {
      src: images[index],
      style: { width: '100%' }
    }),
    width: '60%',
    okText: '关闭'
  });
};

// 返回列表
const goBack = () => {
  router.push('/community/posts');
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 初始化
onMounted(() => {
  loadPost();
});
</script>

<style scoped>
.post-detail-container {
  padding: 24px;
}

.card-title {
  display: flex;
  align-items: center;
}

.post-header {
  margin-bottom: 24px;
}

.post-title {
  font-size: 24px;
  margin-bottom: 16px;
}

.post-meta {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  color: #999;
  margin-bottom: 16px;
}

.post-author {
  display: flex;
  align-items: center;
}

.author-avatar,
.comment-avatar {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  color: white;
  margin-right: 8px;
}

.post-content {
  white-space: pre-wrap;
  line-height: 1.6;
  margin-bottom: 24px;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 24px;
}

.post-images img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
}

.post-actions {
  margin: 24px 0;
}

.comment-time {
  font-size: 12px;
  color: #999;
  margin-left: 16px;
}

.comment-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.comment-likes {
  margin-top: 8px;
  color: #999;
}
</style> 